package com.TeaManage.servlet;

import com.TeaManage.util.GokJDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "HomeServlet", urlPatterns = "/HomeServlet")
public class HomeServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            // 获取系统统计数据
            Map<String, Integer> stats = getSystemStats();
            
            // 设置统计数据到request属性
            request.setAttribute("teaCount", stats.get("teaCount"));
            request.setAttribute("categoryCount", stats.get("categoryCount"));
            request.setAttribute("warehouseCount", stats.get("warehouseCount"));
            request.setAttribute("orderCount", stats.get("orderCount"));
            request.setAttribute("supplierCount", stats.get("supplierCount"));
            request.setAttribute("customerCount", stats.get("customerCount"));
            request.setAttribute("purchaseCount", stats.get("purchaseCount"));
            
            // 获取最近的活动数据
//            Map<String, Object> recentData = getRecentData();
//            request.setAttribute("recentOrders", recentData.get("recentOrders"));
//            request.setAttribute("recentPurchases", recentData.get("recentPurchases"));
//            request.setAttribute("lowStockTeas", recentData.get("lowStockTeas"));
            
            // 转发到home.jsp
            request.getRequestDispatcher("/views/home.jsp").forward(request, response);
            
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "获取系统数据失败");
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
    
    /**
     * 获取系统统计数据
     */
    private Map<String, Integer> getSystemStats() throws SQLException {
        Map<String, Integer> stats = new HashMap<>();
        Connection conn = GokJDBCUtil.getConnection();
        
        try {
            // 茶叶品种数量
            String teaSql = "SELECT COUNT(*) as count FROM tea";
            PreparedStatement teaStmt = conn.prepareStatement(teaSql);
            ResultSet teaRs = teaStmt.executeQuery();
            if (teaRs.next()) {
                stats.put("teaCount", teaRs.getInt("count"));
            }
            teaRs.close();
            teaStmt.close();
            
            // 分类数量
            String categorySql = "SELECT COUNT(*) as count FROM tea_category";
            PreparedStatement categoryStmt = conn.prepareStatement(categorySql);
            ResultSet categoryRs = categoryStmt.executeQuery();
            if (categoryRs.next()) {
                stats.put("categoryCount", categoryRs.getInt("count"));
            }
            categoryRs.close();
            categoryStmt.close();
            
            // 仓库数量
            String warehouseSql = "SELECT COUNT(*) as count FROM warehouse";
            PreparedStatement warehouseStmt = conn.prepareStatement(warehouseSql);
            ResultSet warehouseRs = warehouseStmt.executeQuery();
            if (warehouseRs.next()) {
                stats.put("warehouseCount", warehouseRs.getInt("count"));
            }
            warehouseRs.close();
            warehouseStmt.close();
            
            // 订单总数
            String orderSql = "SELECT COUNT(*) as count FROM orders";
            PreparedStatement orderStmt = conn.prepareStatement(orderSql);
            ResultSet orderRs = orderStmt.executeQuery();
            if (orderRs.next()) {
                stats.put("orderCount", orderRs.getInt("count"));
            }
            orderRs.close();
            orderStmt.close();
            
            // 供应商数量
            String supplierSql = "SELECT COUNT(*) as count FROM supplier WHERE status = 1";
            PreparedStatement supplierStmt = conn.prepareStatement(supplierSql);
            ResultSet supplierRs = supplierStmt.executeQuery();
            if (supplierRs.next()) {
                stats.put("supplierCount", supplierRs.getInt("count"));
            }
            supplierRs.close();
            supplierStmt.close();
            
            // 客户数量
            String customerSql = "SELECT COUNT(*) as count FROM customer WHERE status = 1";
            PreparedStatement customerStmt = conn.prepareStatement(customerSql);
            ResultSet customerRs = customerStmt.executeQuery();
            if (customerRs.next()) {
                stats.put("customerCount", customerRs.getInt("count"));
            }
            customerRs.close();
            customerStmt.close();
            
            // 采购单数量
            String purchaseSql = "SELECT COUNT(*) as count FROM purchase";
            PreparedStatement purchaseStmt = conn.prepareStatement(purchaseSql);
            ResultSet purchaseRs = purchaseStmt.executeQuery();
            if (purchaseRs.next()) {
                stats.put("purchaseCount", purchaseRs.getInt("count"));
            }
            purchaseRs.close();
            purchaseStmt.close();
            
        } finally {
            conn.close();
        }
        
        return stats;
    }
    
    /**
     * 获取最近的活动数据
     */
//    private Map<String, Object> getRecentData() throws SQLException {
//        Map<String, Object> data = new HashMap<>();
//        Connection conn = GokJDBCUtil.getConnection();
//
//        try {
//            // 最近订单数量（本月）
//            String recentOrdersSql = "SELECT COUNT(*) as count FROM orders WHERE MONTH(order_date) = MONTH(CURDATE()) AND YEAR(order_date) = YEAR(CURDATE())";
//            PreparedStatement recentOrdersStmt = conn.prepareStatement(recentOrdersSql);
//            ResultSet recentOrdersRs = recentOrdersStmt.executeQuery();
//            if (recentOrdersRs.next()) {
//                data.put("recentOrders", recentOrdersRs.getInt("count"));
//            }
//            recentOrdersRs.close();
//            recentOrdersStmt.close();
//
//            // 最近采购数量（本月）
//            String recentPurchasesSql = "SELECT COUNT(*) as count FROM purchase WHERE MONTH(purchase_date) = MONTH(CURDATE()) AND YEAR(purchase_date) = YEAR(CURDATE())";
//            PreparedStatement recentPurchasesStmt = conn.prepareStatement(recentPurchasesSql);
//            ResultSet recentPurchasesRs = recentPurchasesStmt.executeQuery();
//            if (recentPurchasesRs.next()) {
//                data.put("recentPurchases", recentPurchasesRs.getInt("count"));
//            }
//            recentPurchasesRs.close();
//            recentPurchasesStmt.close();
//
//            // 低库存茶叶数量（假设库存小于10为低库存）
//            String lowStockSql = "SELECT COUNT(*) as count FROM tea WHERE stock < 10";
//            PreparedStatement lowStockStmt = conn.prepareStatement(lowStockSql);
//            ResultSet lowStockRs = lowStockStmt.executeQuery();
//            if (lowStockRs.next()) {
//                data.put("lowStockTeas", lowStockRs.getInt("count"));
//            }
//            lowStockRs.close();
//            lowStockStmt.close();
//
//        } finally {
//            conn.close();
//        }
//
//        return data;
//    }
}
